﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _05_Thread_线程练习_1
{
    public enum threadState
    {
        /// <summary>
        /// 等待运行
        /// </summary>
        Wait,
        /// <summary>
        /// 运行中
        /// </summary>
        Running,
        /// <summary>
        /// 阻塞中
        /// </summary>
        Join
    }

    public class ThreadClass
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 线程状态
        /// </summary>
        public threadState theState { get; set; } = threadState.Wait;//等待运行

        //线程
        public Thread thread { get; set; }
        //当前进度
        public int Value { get; set; }

        /// <summary>
        /// 线程运行响应事件
        /// </summary>
        public event Func<int, int> RunEvent;

        public event Action StartAndAbortEvent;//线程启动与终止事件
        public event Action SuspendAndResumeEvent;//线程挂起与唤醒事件

        /// <summary>
        /// 手动同步事件
        /// </summary>
        public ManualResetEvent manualResetEvent { get; set; }

        /// <summary>
        /// 线程启动
        /// </summary>
        public void Strart()
        {
            theState = threadState.Running;//运行中
            manualResetEvent = new ManualResetEvent(true);
            thread = new Thread(DoWork);
            thread.IsBackground = true;
            thread.Start();
            //控制界面响应
            StartAndAbortEvent.Invoke();
        }

        public void DoWork()
        {
            for (int i = 0; i <= 100; i++)
            {
                //记录当前进度
                Value = i;
                //线程阻塞
                manualResetEvent.WaitOne(); 
                //更新进度条与label标签,获取界面的延时时间
                int delay = RunEvent.Invoke(i);
                //延时
                Thread.Sleep(delay);
            }
        }

        /// <summary>
        /// 线程终止
        /// </summary>
        public void Abort()
        {
            theState = threadState.Wait;//等待运行
            thread.Abort();
            //控制界面响应
            StartAndAbortEvent.Invoke();
        }

        /// <summary>
        /// 线程挂起
        /// </summary>
        public void Suspend()
        {
            if (theState != threadState.Join)
            {
                SuspendAndResumeEvent?.Invoke();//界面时间响应
            }            
            theState = threadState.Join;//阻塞中
            manualResetEvent.Reset();


        }

        /// <summary>
        /// 线程唤醒
        /// </summary>
        public void Resume()
        {
            theState = threadState.Running;//运行中
            manualResetEvent.Set();
            SuspendAndResumeEvent?.Invoke();
        }

    }
}
